import "./ZTlogin.css";
import { PhoneOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { Form, Button, Input, message, FormInstance, Row, Col } from "antd";
import api from '../../api/index'
import { useNavigate } from 'react-router-dom';
import { useState, useEffect, createRef } from 'react';
import React from 'react';
interface LoginFormValues {
    phone: string;
    verificationCode: string;
}
interface CaptchaInstance {
    verify: (callback: (param: string) => void) => void;
    refresh: () => void;
}

interface CaptchaConfig {
    SceneId: string;
    prefix: string;
    mode: 'popup' | 'bind';
    element: string;
    button: string;
    captchaVerifyCallback: (param: string) => Promise<{ captchaResult: boolean; bizResult?: boolean }>;
    onBizResultCallback: () => void;
    getInstance: (instance: CaptchaInstance) => void;
    slideStyle: { width: number; height: number };
    language: 'cn' | 'tw' | 'en';
}

declare global {
    interface Window {
        initAliyunCaptcha: (config: CaptchaConfig) => void;
    }
}

function ZTForgetPasswordLogin() {
    const navigate = useNavigate();
    const [countdown, setCountdown] = useState(0);
    const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);
    const form = createRef<FormInstance<LoginFormValues>>();
    const [messageApi, contextHolder] = message.useMessage();

    const getVerificationCode = async () => {
        const formInstance = form.current;
        if (!formInstance) {
            return;
        }
        const phoneNumber = formInstance.getFieldValue('phone');
        if (!phoneNumber) {
            message.error('请输入手机号码');
            return;
        }
        await api.post('/sendVerificationCode', { phone: phoneNumber });
        message.success('验证码已发送，请查收');
        setCountdown(60);
        const newTimer = setInterval(() => {
            setCountdown(prevCountdown => {
                if (prevCountdown > 0) {
                    return prevCountdown - 1;
                } else {
                    clearInterval(newTimer);
                    setTimer(null);
                    return 0;
                }
            });
        }, 1000);
        setTimer(newTimer);

    };

    const onFinish = async (values: LoginFormValues) => {
        console.log(values);

        try {
            const response = await api.post('/loginByPhone', values);
            const { username } = response.data;
            localStorage.setItem('user', JSON.stringify({ username }));
            console.log('登录成功');
            // 登录成功后跳转到仪表盘页面
            navigate('/CXF');
        } catch (error:any) {
                messageApi.open({
                    type:'error',
                    content:error.response.data.message
                })
        }
    };
    const captcha = React.useRef<CaptchaInstance | null>(null);

    const getInstance = (instance: CaptchaInstance) => {
        captcha.current = instance;
    };
    const captchaVerifyCallback = async (captchaVerifyParam: any) => {
        // 1.向后端发起业务请求，获取验证码验证结果和业务结果

        let res = false;

        console.log("验证");

        const result = await fetch('http://localhost:3000/zt/afsCheck', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                captchaVerifyParam
            })
        }).then(res => res.json())
            .then(data => {
                console.log(data);
                if (data.code === 200) {
                    console.log('验证通过');
                    res = true;

                }
            })
        return {
            captchaResult: res, // 验证码验证是否通过，boolean类型，必选
            bizResult: true, // 业务验证是否通过，boolean类型，可选；若为无业务验证结果的场景，bizResult可以为空
        }
        //console.log(captchaVerifyParam);
    }

    // 验证通过后调用
    const onBizResultCallback: () => void = () => {
        getVerificationCode()
    }

    useEffect(() => {
        window.initAliyunCaptcha({
            SceneId: '148ip69a', // 场景ID。根据步骤二新建验证场景后，您可以在验证码场景列表，获取该场景的场景ID
            prefix: '1iitvn', // 身份标。开通阿里云验证码2.0后，您可以在控制台概览页面的实例基本信息卡片区域，获取身份标
            mode: 'popup', // 验证码模式。popup表示要集成的验证码模式为弹出式。无需修改
            element: '#captcha-element', // 页面上预留的渲染验证码的元素，与原代码中预留的页面元素保持一致。
            button: '#captcha-button', // 触发验证码弹窗的元素。button表示单击登录按钮后，触发captchaVerifyCallback函数。您可以根据实际使用的元素修改element的值
            captchaVerifyCallback: captchaVerifyCallback, // 业务请求(带验证码校验)回调函数，无需修改
            onBizResultCallback: onBizResultCallback, // 业务请求结果回调函数，无需修改
            getInstance: getInstance, // 绑定验证码实例函数，无需修改
            slideStyle: {
                width: 360,
                height: 40,
            }, // 滑块验证码样式，支持自定义宽度和高度，单位为px。其中，width最小值为320 px
            language: 'cn', // 验证码语言类型，支持简体中文（cn）、繁体中文（tw）、英文（en）
        });
        return () => {

            // 必须删除相关元素，否则再次mount多次调用 initAliyunCaptcha 会导致多次回调 captchaVerifyCallback
            document.getElementById('aliyunCaptcha-mask')?.remove();
            document.getElementById('aliyunCaptcha-window-popup')?.remove();
        }
    }, []);
    useEffect(() => {
        return () => {
            if (timer) {
                clearInterval(timer);
            }
        };
    }, [timer]);

    return (
        <>
            {contextHolder}
            <div>
                <h4>通过手机号验证登录</h4>
                <div style={{ width: '80%', margin: 'auto' }}>
                    <Form
                        ref={form}
                        name="phone_login"
                        className="login-form"
                        onFinish={onFinish}
                    >
                        <Form.Item
                            name="phone"
                            rules={[{ required: true, message: '手机号码不能为空' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' }]}
                        >
                            <Input
                                prefix={<PhoneOutlined className="site-form-item-icon" />}
                                placeholder="请输入手机号码" />
                        </Form.Item>
                        <Form.Item extra="We must make sure that your are a human.">
                            <Row gutter={8}>
                                <Col span={15}>
                                    <Form.Item
                                        name="verificationCode"
                                        rules={[{ required: true, message: '验证码不能为空' }]}
                                    >
                                        <Input
                                            prefix={<CheckCircleOutlined className="site-form-item-icon" />}
                                            placeholder="请输入验证码" />
                                    </Form.Item>
                                </Col>
                                <Col span={9}>
                                    <Button
                                        type="primary"
                                        disabled={countdown > 0}
                                        className="login-form-button"
                                        id="captcha-button"
                                    >
                                        {countdown > 0 ? `${countdown}s后重试` : '获取验证码'}
                                    </Button>
                                </Col>
                            </Row>
                        </Form.Item>

                        <Form.Item>
                            <Button
                                type="primary"
                                htmlType="submit"
                                className="login-form-button">
                                登录/注册
                            </Button>
                        </Form.Item>
                    </Form>
                </div>

            </div>

        </>
    );
}

export default ZTForgetPasswordLogin;